// ==UserScript==
// @name         AI聊天记录存档
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  为页面添加聊天记录存档功能
// @author       George Cai
// @match        https://chat.deepseek.com/*
// @grant        none
// ==/UserScript==

(function() {
    'use strict';
    
    // 创建并添加按钮到页面左上角
    function createArchiverButton() {
        const button = document.createElement('button');
        button.textContent = '存档对话';  // 更简洁的文字
        button.style.cssText = `
            color:white;
            position: fixed;
            top: 20px;
            left: 20px;
            z-index: 9999;
            padding: 8px 16px;
            background-color: rgba(0, 122, 255, 0.9);  // Apple蓝色
            border: none;
            border-radius: 8px;
            border-color: rgba(0, 122, 255, 0.9);  // Apple蓝色
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
            transition: all 0.2s ease;
            backdrop-filter: blur(10px);
            -webkit-backdrop-filter: blur(10px);
        `;
        
        // 添加悬停和点击效果
        button.addEventListener('mouseenter', () => {
            button.style.backgroundColor = 'rgba(0, 122, 255, 1)';
            button.style.transform = 'scale(1.02)';
        });
        button.addEventListener('mouseleave', () => {
            button.style.backgroundColor = 'rgba(0, 122, 255, 0.9)';
            button.style.transform = 'scale(1)';
        });
        button.addEventListener('mousedown', () => {
            button.style.transform = 'scale(0.98)';
        });
        button.addEventListener('mouseup', () => {
            button.style.transform = 'scale(1)';
        });
        
        button.addEventListener('click', showBlockSelector);
        document.body.appendChild(button);
    }

    // 创建消息提示框
    function showMessage(text, type = 'success') {
        const message = document.createElement('div');
        message.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 12px 24px;
            border-radius: 12px;
            color: white;
            font-size: 14px;
            font-weight: 500;
            z-index: 10001;
            backdrop-filter: blur(10px);
            -webkit-backdrop-filter: blur(10px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            animation: slideIn 0.3s cubic-bezier(0.2, 0.8, 0.2, 1), 
                       fadeOut 0.5s cubic-bezier(0.2, 0.8, 0.2, 1) 2s forwards;
        `;
        
        if (type === 'success') {
            message.style.backgroundColor = 'rgba(52, 199, 89, 0.9)';  // Apple绿色
        } else if (type === 'error') {
            message.style.backgroundColor = 'rgba(255, 59, 48, 0.9)';  // Apple红色
        }
        
        message.textContent = text;
        
        const style = document.createElement('style');
        style.textContent = `
            @keyframes slideIn {
                from { transform: translateX(100%) scale(0.95); opacity: 0; }
                to { transform: translateX(0) scale(1); opacity: 1; }
            }
            @keyframes fadeOut {
                from { transform: translateX(0) scale(1); opacity: 1; }
                to { transform: translateX(20px) scale(0.95); opacity: 0; }
            }
        `;
        document.head.appendChild(style);
        document.body.appendChild(message);
        
        setTimeout(() => {
            message.remove();
            style.remove();
        }, 3000);
    }

    // 创建选择区块的弹窗
    function showBlockSelector() {
        const modal = document.createElement('div');
        modal.style.cssText = `
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%) scale(0.95);
            background-color: rgba(255, 255, 255, 0.95);
            padding: 24px;
            border-radius: 16px;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
            max-height: 80vh;
            overflow-y: auto;
            z-index: 10000;
            min-width: 360px;
            opacity: 0;
            transition: all 0.3s cubic-bezier(0.2, 0.8, 0.2, 1);
            backdrop-filter: blur(20px);
            -webkit-backdrop-filter: blur(20px);
        `;

        // 添加标题
        const title = document.createElement('h3');
        title.textContent = '选择要存档的对话';
        title.style.cssText = `
            margin: 0 0 16px 0;
            font-size: 18px;
            font-weight: 600;
            color: #1d1d1f;
        `;
        modal.appendChild(title);

        const blocks = document.querySelectorAll('.ds-markdown--block');
        
        blocks.forEach((block, index) => {
            const firstP = block.querySelector('p, h3');
            const title = firstP ? firstP.textContent.substring(0, 30) + '...' : `对话 ${index + 1}`;
            
            const blockItem = document.createElement('div');
            blockItem.style.cssText = `
                padding: 12px 16px;
                margin: 8px 0;
                border-radius: 12px;
                cursor: pointer;
                transition: all 0.2s ease;
                background-color: rgba(0, 0, 0, 0.03);
                color: #1d1d1f;
                font-size: 14px;
            `;
            
            blockItem.addEventListener('mouseenter', () => {
                blockItem.style.backgroundColor = 'rgba(0, 122, 255, 0.1)';
                blockItem.style.transform = 'scale(1.01)';
            });
            blockItem.addEventListener('mouseleave', () => {
                blockItem.style.backgroundColor = 'rgba(0, 0, 0, 0.03)';
                blockItem.style.transform = 'scale(1)';
            });
            
            blockItem.textContent = title;
            blockItem.addEventListener('click', () => {
                copyBlockHtml(block, overlay, modal);
            });
            
            modal.appendChild(blockItem);
        });

        const overlay = document.createElement('div');
        overlay.style.cssText = `
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.3);
            backdrop-filter: blur(5px);
            -webkit-backdrop-filter: blur(5px);
            z-index: 9999;
            opacity: 0;
            transition: opacity 0.3s ease;
        `;
        
        document.body.appendChild(overlay);
        document.body.appendChild(modal);
        
        // 触发动画
        requestAnimationFrame(() => {
            overlay.style.opacity = '1';
            modal.style.opacity = '1';
            modal.style.transform = 'translate(-50%, -50%) scale(1)';
        });

        overlay.addEventListener('click', () => {
            modal.style.transform = 'translate(-50%, -50%) scale(0.95)';
            modal.style.opacity = '0';
            overlay.style.opacity = '0';
            setTimeout(() => {
                overlay.remove();
                modal.remove();
            }, 300);
        });
    }

    // HTML转Markdown的辅助函数
    function convertHtmlToMarkdown(element) {
        let markdown = '';
        
        function processNode(node) {
            if (node.nodeType === Node.TEXT_NODE) {
                return node.textContent;
            }
            
            let result = '';
            const nodeName = node.nodeName.toLowerCase();
            
            // 添加表格处理逻辑
            if (nodeName === 'table') {
                const rows = node.querySelectorAll('tr');
                if (rows.length === 0) return '';
                
                // 处理表头
                const headerCells = rows[0].querySelectorAll('th');
                if (headerCells.length > 0) {
                    result += '|' + Array.from(headerCells).map(cell => ' ' + processNode(cell).trim() + ' ').join('|') + '|\n';
                    result += '|' + Array(headerCells.length).fill(' --- ').join('|') + '|\n';
                }
                
                // 处理表格内容
                for (let i = (headerCells.length ? 1 : 0); i < rows.length; i++) {
                    const cells = rows[i].querySelectorAll('td, th');
                    if (cells.length > 0) {
                        result += '|' + Array.from(cells).map(cell => ' ' + processNode(cell).trim() + ' ').join('|') + '|\n';
                    }
                }
                
                result += '\n';
                return result;
            }
            
            // 检查是否是代码块
            if (node.classList && node.classList.contains('md-code-block')) {
                // 获取语言信息
                const infoString = node.querySelector('.md-code-block-infostring');
                const language = infoString ? infoString.textContent : '';
                
                // 获取代码内容
                const pre = node.querySelector('pre');
                if (pre) {
                    result += '\n```' + language + '\n';
                    result += pre.textContent;
                    result += '\n```\n\n';
                    return result;
                }
            }
            
            switch (nodeName) {
                case 'h1':
                case 'h2':
                case 'h3':
                case 'h4':
                case 'h5':
                case 'h6':
                    const level = nodeName.charAt(1);
                    result += `${'#'.repeat(parseInt(level))} `;
                    break;
                case 'p':
                    if (node.previousElementSibling) {
                        result += '\n';
                    }
                    
                    // 只有当p标签直接在ds-markdown--block下时才转换strong为h3
                    const isDirectChild = node.parentElement && 
                        node.parentElement.classList && 
                        node.parentElement.classList.contains('ds-markdown--block');
                    
                    if (isDirectChild) {
                        const firstStrong = node.querySelector('strong');
                        if (firstStrong) {
                            result += '### ' + firstStrong.textContent + '\n\n';
                            firstStrong.remove();
                        }
                    }
                    
                    // 检查剩余内容是否包含br标签
                    const brTags = node.getElementsByTagName('br');
                    if (brTags.length > 0) {
                        // 创建临时容器来处理HTML
                        const temp = document.createElement('div');
                        temp.innerHTML = node.innerHTML;
                        
                        // 将br标签替换为特殊标记
                        const parts = temp.innerHTML.split(/<br\s*\/?>/i);
                        parts.forEach(part => {
                            if (part.trim()) {
                                // 创建临时元素来处理每个部分的HTML
                                const partContainer = document.createElement('div');
                                partContainer.innerHTML = part.trim();
                                // 递归处理这部分的HTML
                                result += '- ' + processNode(partContainer) + '\n';
                            }
                        });
                        return result;
                    }
                    break;
                case 'strong':
                    // 只处理不是直接在ds-markdown--block下的p标签中的第一个strong
                    const parentP = node.closest('p');
                    const isDirectChildStrong = parentP && 
                        parentP.parentElement && 
                        parentP.parentElement.classList && 
                        parentP.parentElement.classList.contains('ds-markdown--block') && 
                        parentP.querySelector('strong') === node;
                        
                    if (!isDirectChildStrong) {
                        result += '**';
                    }
                    break;
                case 'ul':
                    if (node.previousElementSibling) {
                        result += '\n';
                    }
                    break;
                case 'li':
                    result += '- ';
                    break;
                case 'hr':
                    result += '\n---\n\n';
                    return result;
                case 'pre':
                    // 如果是独立的pre标签（不在md-code-block内）
                    if (!node.closest('.md-code-block')) {
                        result += '\n```\n';
                        result += node.textContent;
                        result += '\n```\n\n';
                        return result;
                    }
                    break;
                case 'code':
                    // 添加行内代码的处理
                    result += '`';
                    break;
            }
            
            // 处理子节点
            for (const child of node.childNodes) {
                result += processNode(child);
            }
            
            // 处理结束标签
            switch (nodeName) {
                case 'h1':
                case 'h2':
                case 'h3':
                case 'h4':
                case 'h5':
                case 'h6':
                case 'p':
                    if (!node.closest('li')) {  // 如果不在li内，才添加双换行
                        result += '\n\n';
                    }
                    break;
                case 'strong':
                    result += '**';
                    break;
                case 'li':
                    result += '\n';  // 只添加单个换行
                    break;
                case 'ul':
                    result += '\n';  // ul结束后添加单个换行
                    break;
                case 'code':
                    result += '`';
                    break;
            }
            
            return result;
        }
        
        markdown = processNode(element);
        
        // 清理多余的空行，但保留列表格式
        markdown = markdown.replace(/\n{3,}/g, '\n\n')
                 .replace(/\n\n-/g, '\n-');  // 确保列表项之间没有空行
        
        return markdown.trim();
    }

    // 修改复制函数
    function copyBlockHtml(block, overlay, modal) {
        const markdown = convertHtmlToMarkdown(block);
        navigator.clipboard.writeText(markdown).then(() => {
            // 移除遮罩和弹窗
            overlay.remove();
            modal.remove();
            // 显示成功消息
            showMessage('Markdown内容已复制到剪贴板！');
        }).catch(err => {
            console.error('复制失败:', err);
            // 显示错误消息
            showMessage('复制失败，请查看控制台了解详情', 'error');
        });
    }

    // 初始化
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', createArchiverButton);
    } else {
        createArchiverButton();
    }
})(); 